package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

public class AliyunSmsSender {


    private static final String ACCESS_KEY_ID = "LTAI5tLRr1s8bKxoK2CK5uwR";
    private static final String ACCESS_KEY_SECRET = "fKoVGzMRciU5wLXwIWpmfxBQIS4UnM";
    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";
    private static final String TemplateCode = "SMS_466235060";
    private static final String SignName = "泉速充";

    public static Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET);
        // 访问的域名
        config.endpoint = ENDPOINT;
        return new Client(config);
    }

    public static boolean sendSmsCode(String phoneNumber, int code) {

        // 短信模板变量对应的实际值，JSON格式
        JSONObject templateParam = new JSONObject();
        templateParam.put("validateCode", code);
        JSONObject result = sendSms(phoneNumber, TemplateCode, templateParam.toJSONString());

        if (!"OK".equals(result.getString("Code"))) {
            throw new RuntimeException(result.getString("Message"));
        }
        return true;
    }

    public static JSONObject sendSms(String phoneNumber, String templateCode, String templateParam) {
        JSONObject result = new JSONObject();
        try {
            System.err.println("短信参数----" + templateParam);
            System.err.println("收信手机号----" + phoneNumber);
            Client client = createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(SignName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(templateParam);
            SendSmsResponse response = client.sendSms(sendSmsRequest);

            result.put("Code", response.getBody().getCode());
            result.put("Message", response.getBody().getMessage());
            System.err.println("发送短信返回报文---" + result.toJSONString());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}